let ErrorUtils = require('../utils/error/ErrorUtils');
let {User, BaseUserInfo, LearningExperience, UserUploadPic, UserApply, Order} = require('../models');
let lodash = require('lodash');
const {infoLogger, errorLogger} = require('../config').logger;
const Joi = require('joi');
const crypto = require('crypto');
const config = require('../config');
const redis = require('../redis');
let EmailService = require('../service/email');

class AdminLoginService {
    static async index(content) {
        return content;
    }

    static checkValiData(data) {
        let schema = Joi.object({
            username: Joi.string().min(2).max(30).required(),
            password: Joi.string().min(6).max(16).required()
        });
        let result = Joi.validate(data, schema);
        return result;
    }

    /**
     *  用户登录
     * @param data
     * @returns {Promise<void>}
     */
    static async login(data) {
        infoLogger.info('登录开始,请求参数为:', data);
        await AdminLoginService.checkValiData(data);
        if (!data.username) {
            ErrorUtils.throwApiError(ErrorUtils.USERNAME_NOT_EXIST);
        }
        let result = await User.findOne().where("username", data.username);
        if (!result) {
            ErrorUtils.throwApiError(ErrorUtils.USERNAME_NOT_EXIST);
        }
        let password = data.password;
        password = password + config.auth.salt;
        password.toLowerCase();
        const md5 = crypto.createHash('md5');
        md5.update(password);
        password = md5.digest('hex');
        if (password === result.password) {
            //存储用户信息
            await redis.setex(`${config.auth.adminLoginPrefix}${data.username}`, config.auth.adminTtl, JSON.stringify(result));
            //result=lodash.pick(result,['_id','username']);
            return result;
        } else {
            ErrorUtils.throwApiError(ErrorUtils.PASSWORD_ERROR);
        }
        infoLogger.info(">>>>>>登录结束");
    }

    static checkRegisterValiData(data) {
        let schema = Joi.object({
            username: Joi.string().min(3).max(30).required(),
            password: Joi.string().min(6).max(20).required(),
            rePassword: Joi.string().min(3).max(16).required(),
            phone: Joi.string().min(11).max(11).required(),
            idCard: Joi.string().min(5).max(30).required(),
            status: Joi.number().required(),
            name: Joi.string().required(),
            code: Joi.string().required(),//邮箱验证码
        });
        let result = Joi.validate(data, schema);
        return result;
    }

    /**
     *  用户登录
     * @param data
     * @returns {Promise<void>}
     */
    static async register(data) {
        infoLogger.info('>>>>>>注册开始,请求参数为:', data);
        await AdminLoginService.checkRegisterValiData(data);
        if (!data.username) {
            ErrorUtils.throwApiError(ErrorUtils.USERNAME_NOT_EXIST);
        }
        let result = await User.findOne().where("username", data.username);
        if (result) {
            ErrorUtils.throwApiError(ErrorUtils.USERNAME_EXISTS);
        }
        if (!data.phone) {
            ErrorUtils.throwApiError(ErrorUtils.PHONE_NOT_EXISTS);
        }
        if (data.password != data.rePassword) {
            ErrorUtils.throwApiEror(ErrorUtils.TWICE_PASSWORD_NOT_SAME);
        }
        data.status = parseInt(data.status);
        switch (data.status) {
            case 0:
                break;
            case 1:
                break;
            default:
                data.status = 2;
                break;
        }
        data.email = data.username;
        //核验邮箱
        await EmailService.checkEmailCode(data.email, data.code);
        let password = data.password;
        password = password + config.auth.salt;
        password.toLowerCase();
        const md5 = crypto.createHash('md5');
        md5.update(password);
        password = md5.digest('hex');
        data.password = password;
        result = await User.create(data);
        if (!result._id) {
            ErrorUtils.throwApiError(ErrorUtils.INSERT_FAIL);
        }
        await EmailService.delEmailValue(data.email);
        infoLogger.info(">>>>>>注册结束");
        return true;
    }

    static checkVerifyInfoData(data) {
        let schema = Joi.object({
            code: Joi.string().min(5).max(30).required(),
            idCard: Joi.string(),
        });
        let result = Joi.validate(data, schema);
        return result;
    }

    /**
     * 确认申请
     * @param ctx
     * @returns {Promise<boolean>}
     */
    static async findVerifyInfo(ctx) {
        let data = ctx.request.body;
        infoLogger.info('>>>>>:查询申请信息列表开始', data);
        await AdminLoginService.checkVerifyInfoData(data);
        let applyInfo = await UserApply.findOne({
            code: data.code
        }).lean().exec();
        if (!applyInfo) {
            ErrorUtils.throwApiError(ErrorUtils.SELECT_INFO_NOT_EXISTS);
        }
        let userId = applyInfo.userId;
        if (applyInfo.status != 2) {
            ErrorUtils.throwApiError(ErrorUtils.SELECT_INFO_NOT_EXISTS);
        }
        let object = {};
        let baseInfo = await BaseUserInfo.findOne({userId: userId}).lean().exec();
        let learingInfo = await LearningExperience.findOne({userId: userId}).lean().exec();
        let uploadInfo = await UserUploadPic.findOne({userId: userId}).lean().exec();
        let userInfo = await User.findById(userId).lean().exec();
        object.baseInfo = baseInfo;
        object.learingInfo = learingInfo;
        object.uploadInfo = uploadInfo;
        object.userInfo = userInfo;
        infoLogger.info('>>>>>>用户查询接口结束');
        return object;
    }
}

module.exports = AdminLoginService;
